//
//  AppDelegate.swift
//  simpleWeibo

import UIKit
import UserNotifications
import SVProgressHUD
import AFNetworking

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        setupAddtions()
        setupRootWindow()
        loadAppInfo()
        UIViewController.swizzlePresent()
        return true 
    }
    
    private func setupRootWindow() {
        //1创建window 赋值给属性window
        window = UIWindow()
        window?.backgroundColor = UIColor.white
        
        //2 创建根控制器
        let vc = WBMainController()
        //添加到tabBarController的子控制器, 本身已经添加了导航控制器, 所以tabBarController不要添加到导航控制器了
//        let nav = UINavigationController.init(rootViewController: vc)
        
        //3 设置window的根控制器为 nav
        window?.rootViewController = vc
        
        //4 window 成为key并可见
        window?.makeKeyAndVisible()
    }
    

}

/// 应用程序额外初始化
extension AppDelegate {
    fileprivate func setupAddtions() {
        SVProgressHUD.setMinimumDismissTimeInterval(1)
        AFNetworkActivityIndicatorManager.shared().isEnabled = true
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound, .carPlay]) { (success, error) in
                print("授权 " + (success ? "成功" : "失败"))
            }
        } else {
            let notifiSetting = UIUserNotificationSettings(types: [.alert,.badge,.sound], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(notifiSetting)
        }
    }
}

extension AppDelegate {
    
    fileprivate func loadAppInfo() {
        DispatchQueue.global().async {
            //1path
            let url = Bundle.main.url(forResource: "net.json", withExtension: nil)
            
            //2data
            let data = NSData(contentsOf: url!)
            
            //3写入磁盘
            let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let jsonPath = (docDir as NSString).appendingPathComponent("net.json")
            data?.write(toFile: jsonPath, atomically: true)
            
            print("应用程序加载完毕 \(jsonPath)")
        }
        
    }
}

//MARK: - swizzlePresent
extension UIViewController{
    //主要作用是适配ios13，将present变为全屏
      static func swizzlePresent() {

        let orginalSelector = #selector(present(_: animated: completion:))
        let swizzledSelector = #selector(swizzledPresent)

        guard let orginalMethod = class_getInstanceMethod(self, orginalSelector), let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) else{return}

        let didAddMethod = class_addMethod(self,
                                           orginalSelector,
                                           method_getImplementation(swizzledMethod),
                                           method_getTypeEncoding(swizzledMethod))

        if didAddMethod {
          class_replaceMethod(self,
                              swizzledSelector,
                              method_getImplementation(orginalMethod),
                              method_getTypeEncoding(orginalMethod))
        } else {
          method_exchangeImplementations(orginalMethod, swizzledMethod)
        }

      }

      @objc
      private func swizzledPresent(_ viewControllerToPresent: UIViewController,
                                   animated flag: Bool,
                                   completion: (() -> Void)? = nil) {
        if #available(iOS 13.0, *) {
          if viewControllerToPresent.modalPresentationStyle == .automatic || viewControllerToPresent.modalPresentationStyle == .pageSheet{
            viewControllerToPresent.modalPresentationStyle = .fullScreen
          }
        }
        swizzledPresent(viewControllerToPresent, animated: flag, completion: completion)
    }
}


